package com.imooc.dao.impl;

import com.imooc.dao.StudentDAO;
import com.imooc.domain.Student;
import com.imooc.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zghgchao 2017/12/29 14:54
 * StudentDAO访问接口实现类：通过最原始的JDBC的方式操作
 */
public class StudentDAOImpl implements StudentDAO {

    public List<Student> query() {

        List<Student> students = new ArrayList<Student>();

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        String sql = "select id,name,age from student";

        try {
            connection = JDBCUtil.getConnection();
            pstmt = connection.prepareStatement(sql);
            rs = pstmt.executeQuery();

            Student student = null;
            while (rs.next()) {
                student = new Student(rs.getInt("id"), rs.getString("name"), rs.getInt("age"));
                students.add(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection, pstmt, rs);
        }

        return students;
    }

    public void save(Student student) {

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        String sql = "INSERT INTO student (name, age) VALUES (?, ?)";
        try {
            connection = JDBCUtil.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1,student.getName());
            pstmt.setInt(2,student.getAge());
            pstmt.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.release(connection,pstmt,rs);
        }
    }

}
